package org.dromara.iot.config;

import org.dromara.iot.domain.MqttConfigurationProperties;
import org.dromara.iot.handler.ReceiverMessageHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

/**
 * @ClassName MqttInboundConfiguration
 * @Description: 类描述
 * @Author: 罗老师
 * @CreateDate: 2025/6/15 21:24
 */
@Configuration
@EnableConfigurationProperties(MqttConfigurationProperties.class)
public class MqttInboundConfiguration {
    @Autowired
    private MqttConfigurationProperties mqttConfigurationProperties;
    @Autowired
    private MqttPahoClientFactory mqttPahoClientFactory;
    @Autowired
    private ReceiverMessageHandler handler;
    /*
    消息通道
     */
    @Bean
    public MessageChannel messageInboundChannel() {
        return new DirectChannel();
    }
    @Bean
    public MessageProducer messageProducer(){
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(
                mqttConfigurationProperties.getUrl(),
                mqttConfigurationProperties.getSubClientId(),
                        mqttPahoClientFactory,
                        mqttConfigurationProperties.getSubTopic().split(","));
        adapter.setQos(1);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setOutputChannel(messageInboundChannel());
        return adapter;
    }

    @Bean
    @ServiceActivator(inputChannel = "messageInboundChannel")
    public MessageHandler messageHandler(){
        return handler;
    }

}
